<template>
  <div class="user-profile">
    <el-card>
      <div slot="header">
        <span>个人资料</span>
      </div>
      
      <el-form :model="profileForm" :rules="profileRules" ref="profileForm" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="profileForm.username" disabled></el-input>
        </el-form-item>
        
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="profileForm.nickname"></el-input>
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="profileForm.email"></el-input>
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="profileForm.phone"></el-input>
        </el-form-item>
        
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="profileForm.avatar" :src="profileForm.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading">保存修改</el-button>
        </el-form-item>
      </el-form>
      
      <el-divider></el-divider>
      
      <h4>修改密码</h4>
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordForm" label-width="100px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password"></el-input>
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password"></el-input>
        </el-form-item>
        
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password"></el-input>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="changePassword" :loading="pwdLoading">修改密码</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'UserProfile',
  data() {
    // 确认密码验证
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }
    
    return {
      profileForm: {
        username: '',
        nickname: '',
        email: '',
        phone: '',
        avatar: ''
      },
      profileRules: {
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' }
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        phone: [
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ]
      },
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      passwordRules: {
        oldPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度不少于6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认新密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      },
      loading: false,
      pwdLoading: false
    }
  },
  created() {
    this.getUserInfo()
  },
  methods: {
    getUserInfo() {
      const userInfo = this.$store.state.userInfo
      this.profileForm = {
        username: userInfo.username || '',
        nickname: userInfo.nickname || '',
        email: userInfo.email || '',
        phone: userInfo.phone || '',
        avatar: userInfo.avatar || ''
      }
    },
    submitForm() {
      this.$refs.profileForm.validate(async valid => {
        if (valid) {
          this.loading = true
          try {
            const res = await this.$http.put('/users', this.profileForm)
            if (res.data.code === 1) {
              this.$message.success('保存成功')
              // 更新Vuex中的用户信息
              const userInfo = { ...this.$store.state.userInfo, ...this.profileForm }
              this.$store.commit('setUserInfo', userInfo)
            } else {
              this.$message.error(res.data.msg || '保存失败')
            }
          } catch (error) {
            console.error('保存个人资料失败', error)
            this.$message.error('保存失败，请稍后重试')
          } finally {
            this.loading = false
          }
        }
      })
    },
    changePassword() {
      this.$refs.passwordForm.validate(async valid => {
        if (valid) {
          this.pwdLoading = true
          try {
            const res = await this.$http.put('/users/password', this.passwordForm)
            if (res.data.code === 1) {
              this.$message.success('密码修改成功，请重新登录')
              // 退出登录
              this.$store.dispatch('logout')
              this.$router.push('/login')
            } else {
              this.$message.error(res.data.msg || '密码修改失败')
            }
          } catch (error) {
            console.error('修改密码失败', error)
            this.$message.error('密码修改失败，请稍后重试')
          } finally {
            this.pwdLoading = false
          }
        }
      })
    },
    handleAvatarSuccess(res) {
      if (res.code === 1) {
        this.profileForm.avatar = res.data
        this.$message.success('头像上传成功')
      } else {
        this.$message.error(res.msg || '头像上传失败')
      }
    },
    beforeAvatarUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2
      
      if (!isImage) {
        this.$message.error('上传头像图片只能是图片格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      
      return isImage && isLt2M
    }
  }
}
</script>

<style scoped>
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 120px;
  height: 120px;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style> 